package online.sixfish.doubao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import online.sixfish.common.dto.PageDTO;
import online.sixfish.common.dto.UserDetail;
import online.sixfish.common.exception.ApiAsserts;
import online.sixfish.common.pojo.User;
import online.sixfish.common.utils.SecurityUtil;
import online.sixfish.doubao.mapper.BmsFollowMapper;
import online.sixfish.doubao.mapper.BmsTopicMapper;
import online.sixfish.doubao.mapper.UmsUserMapper;
import online.sixfish.doubao.model.dto.LoginDTO;
import online.sixfish.doubao.model.dto.RegisterDTO;
import online.sixfish.doubao.model.entity.Follow;
import online.sixfish.doubao.model.vo.ProfileVO;
import online.sixfish.doubao.service.ArticleService;
import online.sixfish.doubao.service.IBmsFollowService;
import online.sixfish.doubao.service.UserService;
import online.sixfish.common.utils.JwtUtils;
import online.sixfish.common.utils.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;


@Slf4j
@Service
@Primary
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UmsUserMapper, User> implements UserService {


    @Resource
    UmsUserMapper umsUserMapper;

    @Resource
    ArticleService articleService;
    @Resource
    IBmsFollowService iBmsFollowService;
    @Resource
    PasswordEncoder passwordEncoder;

    @Override
    public User executeRegister(RegisterDTO dto) {
        //查询是否有相同用户名的用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, dto.getName()).or().eq(User::getEmail, dto.getEmail());
        User user = baseMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(user)) {
            ApiAsserts.fail("账号或邮箱已存在！");
        }
        User addUser = User.builder()
                .username(dto.getName())
                .alias(dto.getName())
                .password(passwordEncoder.encode(dto.getPass()))
                .email(dto.getEmail())
                .createTime(new Date())
                .status(true)
                .build();
        baseMapper.insert(addUser);

        return addUser;
    }

    @Override
    public User getUserByUsername(String username) {
        return baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }

    @Override
    public String executeLogin(LoginDTO dto) {
        String token = null;

        User user = getUserByUsername(dto.getUsername());
        if (Objects.isNull(user)) {
            ApiAsserts.fail("用户不存在");
        }
        boolean isMatched = passwordEncoder.matches(dto.getPassword(), user.getPassword());
        if (!isMatched) {
            ApiAsserts.fail("密码错误");
        }
        user.setPassword("");
        try {
            token = JwtUtils.createToken(new UserDetail(user));
        } catch (Exception e) {
            log.warn("创建Token异常:{0}", e);
        }
        return token;
    }

    @Override
    public ProfileVO getUserProfile(String id) {
        ProfileVO profile = new ProfileVO();
        User user = baseMapper.selectById(id);
        BeanUtils.copyProperties(user, profile);
        // 用户文章数
        int count = articleService.getUserArticleCount(id);
        profile.setTopicCount(count);
        // 粉丝数
        int followCount = iBmsFollowService.getFollowCount(id);
        profile.setFollowerCount(followCount);
        return profile;
    }

    @Override
    public User findById(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public void updateAvatar(String fileName) {
        String url = "C:\\images\\" + fileName;
        User user = new User();
        user.setId(SecurityUtil.currentUserId());
        user.setAvatar(url);
        umsUserMapper.updateById(user);
    }


}
